package cn.sll.org.service.impl;

import cn.sll.base.service.impl.BaseServiceImpl;
import cn.sll.org.domain.Department;
import cn.sll.org.mapper.DepartmentMapper;
import cn.sll.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper mapper;

//    @Override
//    public List<Department> tree() {
//        List<Department> result = new ArrayList<>();
//        //查询所有数据
//        List<Department> all = mapper.findAll();
//        //在内存中组装数据
//        for (Department dept : all) {
//            if(null == dept.getParentId()){
//                //一级数据
//                result.add(dept);
//            }else{
//                //
//                for (Department parent: all){
//                    if (dept.getParentId().equals(parent.getId())){
//                        parent.getChildren().add(dept);
//                        break;
//                    }
//                }
//
//            }
//        }
//
//        return result;
//    }

    @Override
    public List<Department> tree() {
        List<Department> result = new ArrayList<>();
        //查询所有数据
        List<Department> all = mapper.findAll();
        //将全部数据转换成map key value
        Map<Long, Department> deptMap = all.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
        //在内存中组装数据
        for (Department dept : all) {
            if(null == dept.getParentId()){
                //一级数据
                result.add(dept);
            }else{
                Department parent = deptMap.get(dept.getParentId());
                parent.getChildren().add(dept);
            }
        }

        return result;
    }

}
